const Ws = require('ws')
;((Ws) => {
  const server = new Ws.Server({port: 8000})
  const init = () => {
    bindEvent()
  }
  
  function bindEvent() {
    server.on('open', handleOpen)
    server.on('close', handleClose)
    server.on('error', handleError)
    server.on('connection', handleConnection)
  }
  
  handleOpen = () => {
    console.log('server-open')
  }
  
  handleClose = () => {
    console.log('server-close')
  }
  
  handleError = () => {
    console.log('server-error')
  }
  
  handleConnection = (ws) => {
    ws.on('message', handleMessage)
  }
  
  handleMessage = (msg) => {
    console.log('消息', Buffer.from(msg, 'utf-8').toString('utf-8'))
    
    //  发送至前端
    server.clients.forEach(function (client) {
      client.send(Buffer.from(msg, 'utf-8').toString('utf-8'))
    })
  }
  
  init()
})(Ws)
